package com.xaicode.learn.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:29
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // read client msg
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("ctx: {}", ctx);

        // msg to netty byte buffer
//        ByteBuf byteBuf = (ByteBuf) msg;
//        log.info("read client [{}] msg: {}", ctx.channel().remoteAddress(), byteBuf.toString(CharsetUtil.UTF_8));

        // if business cost too long, use event loop task-queue
        EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.execute(() -> {
            log.info("- task-queue");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ByteBuf byteBuf = (ByteBuf) msg;
            log.info("read client [{}] msg: {}", ctx.channel().remoteAddress(), byteBuf.toString(CharsetUtil.UTF_8));
            // send client a msg
            ctx.writeAndFlush(Unpooled.copiedBuffer("server cost 5 sec to apply read msg", CharsetUtil.UTF_8));
        });

        // schedule task queue
        eventLoop.schedule(() -> {
            log.info("- schedule-task-queue");
            ByteBuf byteBuf = (ByteBuf) msg;
            log.info("read client [{}] msg: {}", ctx.channel().remoteAddress(), byteBuf.toString(CharsetUtil.UTF_8));
            // send client a msg
            ctx.writeAndFlush(Unpooled.copiedBuffer("server cost 5 sec to apply read msg", CharsetUtil.UTF_8));
        }, 5, TimeUnit.SECONDS);

    }

    // read client msg complete
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        log.info("read client msg complete");

        // write and flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("server complete: hello client", CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
